package com.my.socket.nio.v25;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class Server implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    public Server(String host, int port) throws Exception {
        this.selector = Selector.open();
        this.serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port);
        this.serverSocketChannel.bind(inetSocketAddress);
        this.serverSocketChannel.configureBlocking(false);
        this.serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
    }

    @Override
    public void run() {
        try {
            while (true) {
                int select = this.selector.select();
                LOGGER.info("{} event(s) incoming", select);

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    LOGGER.info("incoming socket: {}", socketChannel);
                    socketChannel.read(byteBuffer);
                    LOGGER.info("reading: {}", byteBuffer);
                }
            }

        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", Throwables.getCausalChain(e));
        }

    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        new Thread(server).start();
    }
}
